<template>
  <div id="organization_list">
    <div class="search-box">
      <Row type="flex">
        <Row type="flex"
             justify="start"
             class="search-item-left">
          <Col class="search-item">
          <span class="search-label">组织名称:</span>
          <Input v-model="orgName"
                 placeholder="请输入"
                 :maxlength="20"
                 @on-keyup='filterSpace'></Input>
          </Col>
          <Col class="search-item">
          <span class="search-label">组织状态:</span>
          <Select v-model="orgStatus"
                  @on-change="selectStatus">
            <Option v-for="item in orgStatusList"
                    :value="item.value"
                    :key="item.value">{{ item.label }}</Option>
          </Select>
          </Col>
          <Col class="search-item">
          <Button class="search-btn"
                  type='primary'
                  @click="search">查询</Button>
          </Col>
          <Col class="search-item">
          <Button class="search-btn"
                  @click='reSet'>重置</Button>
          </Col>
        </Row>
        <Row type="flex"
             justify="end"
             class="search-item-right">
          <Col class="search-item">
          <Button class="search-btn"
                  @click='skipLead'
                  v-if="hasPermission('moms:org:import')">导入</Button>
          </Col>
          <Col class="search-item">
          <Button class="search-btn"
                  @click='exportData'
                  :disabled='this.data.length>0 ? false: true'
                  v-if="hasPermission('moms:org:export')">导出</Button>
          </Col>
          <Col class="search-item">
          <Button class="search-btn"
                  type="primary"
                  @click="skipAdd"
                  v-if="hasPermission('moms:org:create')">添加</Button>
          </Col>
        </Row>
      </Row>
    </div>
    <Table stripe
           :height="this.tableHeight"
           class="table-list"
           ref="selection"
           :loading='loading'
           :columns="columns"
           :data="data"
           @on-selection-change='selectItem'>

      <template slot-scope="{ row }"
                slot="member">
        <span v-if="!hasPermission('moms:org:member')">{{ row.userCount }}</span>
        <span class="active"
              @click="skipEmployee(row)"
              v-if="hasPermission('moms:org:member')">{{ row.userCount }}</span>
      </template>
      <template slot-scope="{ row,index }"
                slot="status">
        <span>
          <i-switch v-model="row.status"
                    :disabled="!hasPermission('moms:org:updatestatus')"
                    @on-change="changeSwitch(row,index)">
            <span slot="open">开</span>
            <span slot="close">关</span>
          </i-switch>
        </span>
      </template>
      <template slot-scope="{ row }"
                slot="name">
        <p class="collection-productdesc">{{ row.orgName }}</p>
      </template>
      <template slot-scope="{ row }" slot="orgType">
        <p>{{ row.orgType === 0 ? '职能部门' : row.orgType === 1 ? '门店' : row.orgType === 2 ? '区域' : row.orgType === 3 ? '片区' : row.orgType === 4 ? '总部' : '' }}</p>
      </template>
      <template slot-scope="{ row }"
                slot="desc">
        <p class="collection-productdesc">{{ row.remark }}</p>
      </template>
      <template slot-scope="{ row, index }"
                slot="action">
        <i class="iconsys icondetail"
           title="查看详情"
           @click='skipDetail(row, index)'
           v-if="hasPermission('moms:org:detail')"></i>
        <i class="iconsys iconedit"
           title="编辑"
           @click='skipEdit(row, index)'
           v-if="hasPermission('moms:org:update')"></i>
        <Poptip confirm
                title="你确定要删除吗？"
                @on-ok="ok(row, index)"
                @on-cancel="cancel"
                style="text-align:left">
          <i class="iconsys icondel"
             title="删除"
             v-if="hasPermission('moms:org:delete')"></i>
        </Poptip>
      </template>
    </Table>
    <Row type="flex">
      <Col span="12"
           class="module-menu-nav">
      <Button class="module-menu-margin"
              @click="handleSelectAll"
              v-if="hasPermission(['moms:org:updatestatus', 'moms:org:delete'])">{{btnTitle}}</Button>
      <Dropdown placement="top"
                @on-click='batchAll'
                v-if="hasPermission(['moms:org:updatestatus', 'moms:org:delete'])">
        <Button class="check_all">批量操作</Button>
        <DropdownMenu slot="list"
                      style="text-align:center">
          <DropdownItem name='1'
                        v-if="hasPermission('moms:org:updatestatus')">批量关闭</DropdownItem>
          <DropdownItem name='2'
                        v-if="hasPermission('moms:org:updatestatus')">批量开启</DropdownItem>
          <DropdownItem name='3'
                        v-if="hasPermission('moms:org:delete')">批量删除</DropdownItem>
        </DropdownMenu>
      </Dropdown>
      </Col>
      <Col span="12">
      <div class="page-box">
        <Page :total="total"
              :page-size='pageSize'
              :current='pageIndex'
              show-total
              show-sizer
              @on-change='changePageIndex'
              @on-page-size-change='changePageSize' />
      </div>
      </Col>
    </Row>
  </div>
</template>

<script>
import { getOrgList, disableOrg, enableOrg, delOrg, exportOrgList } from '@/api/system/org'
import { blobToXls } from '@/libs/blobToXls'
export default {
  name: 'organization_list',
  components: {},
  data () {
    return {
      tableHeight: 0,
      btnTitle: '全选',
      isDelete: true,
      loading: true,
      total: 0,
      pageIndex: 1,
      pageSize: 10,
      orgName: '',
      searchOrgName: '',
      orgStatus: '-1',
      orgStatusList: [{ value: '-1', label: '全部' }, { value: '1', label: '启用' }, { value: '0', label: '停用' }],
      selectArrry: [],
      allStatus: true, // 全选状态
      data: [],
      columns: [
        {
          type: 'selection',
          width: 60
        },
        {
          title: '组织名称',
          key: 'orgName',
          slot: 'name'
        },
        {
          title: '组织类型',
          slot: 'orgType'
        },
        {
          title: '组织成员',
          align: 'center',
          key: 'userCount',
          slot: 'member'
        },
        {
          title: '上级组织',
          key: 'parentOrgName'
        },
        {
          title: '排序号',
          key: 'sortNum'
        },
        {
          title: '组织描述',
          // width: 230,
          key: 'remark',
          slot: 'desc'
        },
        {
          title: '操作时间',
          key: 'updateTime'
        },
        {
          title: '组织状态',
          slot: 'status'
        }
      ]
    }
  },
  watch: {
    '$route' (newRoute) {
      if (newRoute.name === 'organization_list') {
        // this.pageIndex = 1
        this.getData()
      }
    },
    selectArrry (val) {
      if (val.length === this.data.length && this.data.length !== 0) {
        this.btnTitle = '取消全选'
        this.allStatus = false
      } else {
        this.btnTitle = '全选'
        this.allStatus = true
      }
    }
  },
  methods: {
    // 导出
    exportData () {
      exportOrgList({
        fileName: 'org',
        type: 'EXCEL'
      }).then(res => {
        if (res.status === 200) {
          blobToXls(res.data, 'department')
        }
      })
    },
    filterSpace () {
      this.orgName = this.orgName.replace(/\s+/g, '')
    },
    search () {
      this.searchOrgName = this.orgName
      this.pageIndex = 1
      this.getData()
    },
    reSet () {
      this.searchOrgName = ''
      this.orgName = ''
      this.orgStatus = '-1'
      this.pageIndex = 1
      this.pageSize = 10
      this.getData()
    },
    selectStatus () {
      this.pageIndex = 1
      this.getData()
    },
    changeSwitch (row, index) {
      let paramster = { load: { 'merchantId': this.$store.state.user.merchantId, id: row.id }, valite: { status: row.status, index: index } }
      this.$set(this.data[index], 'status', row.status)
      if (row.status) {
        this.open(paramster)
      } else {
        this.close(paramster)
      }
    },
    // 开启
    open (data) {
      enableOrg(data.load).then(res => {
        if (res.status === 200) {
          if (res.data.status === 200) {
            if (data.load.idList) {
              this.data.forEach((ele, idx) => {
                this.selectArrry.forEach(item => {
                  if (ele.id === item.id) {
                    this.$set(this.data[idx], 'status', true)
                  }
                })
              })
              this.$Message.success('批量开启成功！')
              // this.getData()
              this.selectArrry = []
            } else {
              this.$set(this.data[data.valite.index], 'status', true)
              this.$Message.success('开启成功！')
            }
          } else {
            if (data.load.idList) {
            } else {
              this.$nextTick(() => {
                this.$set(this.data[data.valite.index], 'status', !data.valite.status)
              })
            }
            this.$Message.error(`${res.data.error}`)
          }
        }
      })
    },
    // 关闭
    close (data) {
      disableOrg(data.load).then(res => {
        if (res.status === 200) {
          if (res.data.status === 200) {
            if (data.load.idList) {
              this.data.forEach((ele, idx) => {
                this.selectArrry.forEach(item => {
                  if (ele.id === item.id) {
                    this.$set(this.data[idx], 'status', false)
                  }
                })
              })
              this.$Message.success('批量关闭成功！')
              this.selectArrry = []
            } else {
              this.$set(this.data[data.valite.index], 'status', false)
              this.$Message.success('关闭成功！')
            }
          } else {
            if (data.load.idList) {
            } else {
              this.$nextTick(() => {
                this.$set(this.data[data.valite.index], 'status', !data.valite.status)
              })
            }
            this.$Message.error(`${res.data.error}`)
          }
        }
      })
    },
    // 删除
    del (data) {
      delOrg(data.load).then(res => {
        this.isDelete = true
        if (res.data.status === 200) {
          if (this.selectArrry.length > 0) {
            this.$Message.success('批量删除成功！')
            this.selectArrry = []
          } else {
            this.$Message.success('删除成功！')
          }
          this.getData()
        } else {
          this.$Message.error(`${res.data.error}`)
        }
      })
    },
    skipAdd () {
      this.$router.push({ path: '/system/organization_create' })
    },
    skipDetail (row, index) {
      this.$router.push({ name: 'organization_detail', params: { id: row.id } })
    },
    skipEdit (row, index) {
      this.$router.push({ name: 'organization_edit', params: { id: row.id } })
    },
    skipEmployee (row) {
      this.$router.push({ name: 'organization_employee', params: { id: row.id } })
    },
    skipLead () {
      this.$router.push({ name: 'organization_import' })
    },
    cancel () { },
    ok (row, index) {
      if (this.isDelete) {
        if (!this.isDelete) {
          return
        }
        this.isDelete = false
        if (row.status) {
          this.$Message.error('组织为启用状态不可删除')
          setTimeout(() => {
            this.isDelete = true
          }, 400)
        } else {
          setTimeout(() => {
            let data = { load: { 'merchantId': this.$store.state.user.merchantId, id: row.id } }
            this.del(data)
          }, 200)
        }
      }
    },
    // 批量操作
    batchAll (val) {
      if (this.selectArrry.length > 0) {
        let flag = true
        let arr = []
        this.selectArrry.forEach(item => {
          arr.push(item.id)
          if (item.status) {
            flag = false
          }
        })
        let param = { load: { 'merchantId': this.$store.state.user.merchantId, idList: arr }, valite: {} }
        this.$Modal.confirm({
          title: val === '1' ? '确认批量关闭吗？' : val === '2' ? '确认批量开启吗？' : '确认批量删除吗？',
          onOk: () => {
            if (val === '1') {
              this.close(param)
            } else if (val === '2') {
              this.open(param)
            } else {
              if (flag) {
                this.del(param)
              } else {
                this.$Message.error('组织为启用状态时不可删除')
              }
            }
          },
          onCancel: () => { }
        })
      } else {
        this.$Message.error('请至少选择一项操作')
      }
    },
    handleSelectAll () {
      // this.allStatus = !this.allStatus
      this.$refs.selection.selectAll(this.allStatus)
    },
    selectItem (val) {
      // this.selectArrry = val.map(item => {
      //   return { id: item.id, status: item.status }
      // })
      this.selectArrry = val
    },
    changePageIndex (page) {
      this.pageIndex = page
      this.getData()
    },
    changePageSize (size) {
      this.pageIndex = 1
      this.pageSize = size
      this.getData()
    },
    getData () {
      this.loading = true
      this.tableHeight = 0
      getOrgList({ 'merchantId': this.$store.state.user.merchantId, pageIndex: this.pageIndex, pageSize: this.pageSize, orgName: this.searchOrgName, status: this.orgStatus === '-1' ? '' : this.orgStatus }).then(res => {
        if (res.data.status === 200) {
          this.loading = false
          this.selectArrry = []
          this.data = res.data.data.records
          this.total = res.data.data.total
          if (res.data.data.records && res.data.data.records.length >= 10) {
            this.tableHeight = 520
          }
          this.data.forEach(ele => {
            ele.status = !!ele.status
          })
          if (res.data.data.records.length / this.pageSize === 0) {
            if (this.pageIndex > 1) {
              this.pageIndex--
              this.getData()
            }
          }
        } else {
          this.loading = false
          this.$Message.error(`${res.data.error}`)
        }
      }).catch((err) => {
        this.loading = false
        this.$Message.error(`${err}`)
      })
    }
  },
  mounted () {
    this.getData()
    if (this.hasPermission(['moms:org:detail', 'moms:org:update', 'moms:org:delete'])) {
      this.columns.push({
        title: '操作',
        slot: 'action',
        width: 200
      })
    }
  }
}
</script>

<style lang="less">
#organization_list {
  .active {
    color: #2d8cf0;
    // border-bottom: 1px solid #2d8cf0;
    cursor: pointer;
  }
  .search-box {
    .search-item-left {
      width: 70%;
    }
    .search-item-right {
      width: 30%;
    }
  }
  .table-list {
    .collection-productdesc {
      max-height: 38px;
      display: -webkit-box;
      -webkit-box-orient: vertical;
      -webkit-line-clamp: 2;
      overflow: hidden;
    }
  }
}
</style>
